package com.tjsinfo.tjsoa.fileExpress.action;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Locale;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.apache.struts.upload.FormFile;
import org.apache.struts.util.MessageResources;

import com.tjsinfo.tjsoa.common.FileUploadForm;
import com.tjsinfo.tjsoa.common.ToolKit;

public class AJAXFileUploadAction extends DispatchAction  {
	public ActionForward uploader(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws IOException {
		InputStream is=null;
		OutputStream os=null;
        try {
        	FileUploadForm upFormForm = (FileUploadForm) form;
        	FormFile myFile = upFormForm.getUploadFile();
            is = myFile.getInputStream();

			String fileAllName = myFile.getFileName();
			String fileType=fileAllName.substring(fileAllName.lastIndexOf(".")+1, fileAllName.length());//文件后缀
			int fileSize=myFile.getFileSize();
			if(fileSize>1048576*40){
				response.getWriter().print("{'fileName':'文件上传失败,单个文件不允许大于40M!','oldFileName':'false'}");
				return null;
			}
			
			String uploadFile=ToolKit.getProperties("com/tjsinfo/tjsoa/system/properties/systemResource_zh_CN.properties", this).getProperty("system.uploadFile.tempFilePath");
			
			UUID uuid = UUID.randomUUID();
            
            File file = new File(uploadFile + uuid+"."+fileType);//指定文件存储的路径和文件名
            os = new FileOutputStream(file);
            byte[] b = new byte[1024];
            int len = 0;
            while((len = is.read(b)) != -1){
                os.write(b, 0, len);
            }
			response.getWriter().print("{'fileName':'"+uuid+"."+fileType+"','oldFileName':'"+fileAllName+"','fileSize':'"+fileSize+"'}");
			return null;
        } catch (Exception e) {
            e.printStackTrace();
			return null;
        } finally{
        	if(os!=null){
        		os.close();
        		is.close();
        	}
        }
    }
	public ActionForward deleted(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) {
        try {
			String uploadFile=ToolKit.getProperties("com/tjsinfo/tjsoa/system/properties/systemResource_zh_CN.properties", this).getProperty("system.uploadFile.tempFilePath");
			
        	String fileName=request.getParameter("file");
        	File file=new File(uploadFile+fileName);
        	file.delete();
        	response.getWriter().print("{'fileName':'"+fileName+"','msg':'文件成功删除!'}");
			return null;
        } catch (Exception e) {
            e.printStackTrace();
			return null;
        } 
    }

}
